'use strict';

angular.module('app.view.fan-data-problem')
    .config(['$stateProvider', function($stateProvider) {
        $stateProvider.state('incomplete-AR', {
            url: '/views/fan-data-problem/incomplete-AR',
            views: {
                'navigation': {
                    templateUrl: 'views/header/navigation.html',
                    controller: 'navigationCtrl'
                },
                'sidebar': {
                    templateUrl: 'views/sidebar/sidebar-fan-data-problem.html',
                    controller: 'sidebarCtrl'
                },
                'content': {
                    templateUrl: 'views/fan-data-problem/incomplete/incomplete-AR.html',
                    controller: 'incompleteARCtrl'
                }
            }
        })
    }])

    .controller('incompleteARCtrl', ['$scope', 'Upload', 'communicationService',

        function($scope, Upload, communicationService) {

            $scope.regressionSize = 10;
            $scope.outputPath = "result.csv";


            // 输入数据table
            $scope.inputDataTable = [];
            // 填充空值结果的table
            $scope.repairDataTable = [];

            $scope.showChart=false;
            $scope.chartTitle = "";

            // 源数据和修复后的数据，用于echarts展示
            $scope.inputData= [];
            $scope.repairData = [];

            // echarts曲线
            $scope.chartSeries = [];

            // 空值的填充。如果输入数据为空，则取得对应的填充值；如果输入数据不为空，则不进行填充。
            $scope.$watch("repairDataTable", function(newValue, oldValue){
                if(newValue === oldValue)
                    return;

                let data = [];
                for(let i = 0; i < $scope.repairDataTable.allData.length; i++)
                {
                    if($scope.inputData[i]===""
                        || (i > 0 && $scope.inputData[i-1] === "")
                        || (i + 1 < $scope.inputData.length && $scope.inputData[i+1] === ""))
                        data.push($scope.repairDataTable.allData[i][1]);
                    else
                        data.push(null);
                }
                $scope.repairData = data;


            });

            // 选择一列，展示此列的图
            $scope.$watch("usedAttr", function(newValue, oldValue){
                if(newValue === oldValue)
                    return;

                $scope.repairData = [];

                newValue = newValue.toString();

                if("header" in $scope.inputDataTable && $.inArray(newValue, $scope.inputDataTable.header) !== -1)
                {
                    let data = [];
                    for (let i = 0; i < $scope.inputDataTable.header.length; i++)
                        if($scope.inputDataTable.header[i] === newValue)
                            for(let j = 0; j < $scope.inputDataTable.allData.length; j++)
                                data.push($scope.inputDataTable.allData[j][i]);

                    $scope.chartTitle = $scope.usedAttr;
                    $scope.inputData = data;
                    $scope.showChart = true;
                }
                else
                {
                    $scope.showChart = false;
                }
            });



            // 绘制echarts图，设置echarts的series
            $scope.$watch("{inputData:inputData, repairData:repairData}", function(newValue, oldValue){
                if(newValue === oldValue)
                    return;

                let inputData = $scope.inputData;
                let repairData = $scope.repairData;
                let chartSeries = [];

                let inputSeries = {
                    name: '原数据',
                    type: 'line',
                    data: inputData,
                    symbol: 'circle',
                    symbolSize: 1,
                    lineStyle: {
                        normal: {
                            color: '#8a8c8e'
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#8a8c8e'
                        }
                    }
                };
                chartSeries.push(inputSeries);

                if(repairData.length !== 0)                  // 展示修复结果
                {
                    let repairSeries =
                    {
                        name: '修复后的数据',
                        type: 'line',
                        data: repairData,
                        symbol: 'circle',
                        symbolSize: 1,
                        lineStyle: {
                        normal: {
                            color: '#1E90FF'
                        }
                    },
                        itemStyle: {
                            normal: {
                                color: '#1E90FF'
                            }
                        }
                    };
                    chartSeries.push(repairSeries);
                }
                $scope.chartSeries = chartSeries;
            }, true);

            // 修复
            $scope.run = function() {
                communicationService.post('/api/fan-data-problem/incomplete-AR', {
                    inputFilename: $scope.inputPath,
                    outputFilename: $scope.outputPath,
                    usedAttr: $scope.usedAttr,
                    regressionSize: $scope.regressionSize
                }).then(function(data){
                    if (!(data instanceof Array)) {
                        data = [data];
                    }
                    let dataTables = [];
                    for (let table of data) {
                        dataTables.push({
                            header: table.header,
                            allData: table.dataList,
                            dataList: table.dataList.slice(0, 100),
                            more: table.dataList.length > 100
                        });
                    }
                    $scope.repairDataTable = dataTables[0];


                    let key = 0, value = 0;
                    for(let i = 0; i < $scope.repairDataTable.allData.length; i++)
                    {
                        if($scope.inputData[i]==="")
                            key++;
                        else
                            value++;
                    }
                    communicationService.post('/api/fan-data-problem/statistics', {
                        operation: "update",
                        id: "0",
                        key: key,
                        value: value,
                    }).then(function(){
                        console.log("incomplete-ar-statistics: ("+key+","+value+")");
                    }, function (err) {
                        console.warn("incomplete-ar-statistics: " + err);
                    });


                }, function(err) {
                    console.warn(err);
                });
            };

            $scope.uploadFiles = function (file, errFiles) {

                $scope.f = file;
                $scope.errFile = errFiles && errFiles[0];
                if (file) {
                    file.upload = Upload.upload({
                        url: '/api/chooseFile',
                        data: {file: file}
                    });

                    file.upload.then(function (response) {
                        $scope.inputPath = response.data.fileName;
                        $scope.preview();

                    }, function (error) {
                        console.log(error);
                    }, function (evt) {});
                }
            };

            $scope.preview = function() {
                $scope.showChart = false;
                communicationService.get('/api/data/csv', {
                    filename: $scope.inputPath
                }).then(function(data){
                    if (!data) {
                        return;
                    }
                    if (!(data instanceof Array)) {
                        data = [data];
                    }
                    let dataTables = [];
                    for (let table of data) {
                        dataTables.push({
                            header: table.header,
                            allData: table.dataList,
                            dataList: table.dataList.slice(0, 100),
                            more: table.dataList.length > 100
                        });
                    }
                    $scope.inputDataTable = dataTables[0];
                    $scope.autoCompleteAttrs = dataTables[0].header;

                }, function(err) {
                    console.warn(err);
                })
            }
    }]);
